from math import log
import operator

def createDataSet():
    dataSet =  [[1, 1, 'yes'],
                [1, 1, 'yes'],
                [1, 0, 'no'],
                [0, 1, 'no'],
                [0, 1, 'no']]
    labels = ['no surfacing','flippers']
    return dataSet, labels

def calcShannoEnt(dataSet):
    numEntries = len(dataSet)
    labelCounts = {}
    shannoEntropy = 0.0
    for featVec in dataSet:
        currentLabel = featVec[-1]
        if currentLabel not in labelCounts.keys():
            labelCounts[currentLabel]  = 0
        labelCounts[currentLabel] += 1
    for key in labelCounts:
        prob = float(labelCounts[key]) /numEntries
        shannoEntropy -= prob * log(prob,2)
    return shannoEntropy

def splitDataSet(dataSet,axis,value):
    subDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:
            reduceFeatVec = featVec[:axis]
            reduceFeatVec.extend(featVec[axis+1:])
            subDataSet.append(reduceFeatVec)
    return subDataSet

def chooseBestFeatureToSplit(dataSet):
    bestInfoGain = 0.0
    bestFeat = -1
    baseEntropy = calcShannoEnt(dataSet)
    numFeatures = len(dataSet[0]) -1
    for i in range(numFeatures):
        featList = [ example[i] for example in dataSet ] 
        uniqueVals = set(featList)
        newEntropy = 0
        for value in uniqueVals:
            subDataSet = splitDataSet(dataSet,i,value)
            prob = len(subDataSet) / float(len(dataSet))
            newEntropy += prob * calcShannoEnt(subDataSet)
        infoGain = baseEntropy - newEntropy
        if(infoGain > bestInfoGain):
            bestInfoGain = infoGain
            bestFeat = i
    return bestFeat

def majorityCnt(classList):
    classCount = {}
    for c in classList:
        if c not in classCount: classCount[c] = 0
        classCount[c] += 1
    sortedClassCount = sorted( classCount.items(), key=operator.itemgetter(1), reverse=True )
    return sortedClassCount[0][0]


def createTree(dataSet,labels):
    classList = [ example[-1] for example in dataSet ]
    if classList.count(classList[0]) == len(classList[0]):
        return classList[0]
    if len(dataSet[0]) == 1:
        return majorityCnt(classList)
    bestFeat = chooseBestFeatureToSplit(dataSet)
    bestFeatLabel = labels[bestFeat]
    myTree = {bestFeatLabel: {}}
    del(labels[bestFeat])
    featValues = [featVec[bestFeat] for featVec in dataSet]
    uniqueVals = set(featValues)
    for featVal in uniqueVals:
        subLabels = labels[:]
        myTree[bestFeatLabel][featVal] = createTree( splitDataSet(dataSet,bestFeat,featVal),subLabels )
    return myTree

 
 
 
 
